﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using System.Device.Location;
using LinqToTwitter;

namespace MolfMolfMolf
{
    public partial class ResultDetailPage : PhoneApplicationPage
    {
        private Club currentClub;
        private GeoCoordinateWatcher watcher;

        public ResultDetailPage()
        {
            InitializeComponent();
            watcher = new GeoCoordinateWatcher();

            if (PhoneApplicationService.Current.State.ContainsKey("club"))
            {
                currentClub = (Club)PhoneApplicationService.Current.State["club"];
                mapClubDetails();
                initAppBar();
            }
        }

        private void mapClubDetails()
        {
            //implementation
            ClubName.Text = currentClub.ClubName;
            ClubPhone.Text = "Telephone: "+ currentClub.ClubPhone;
            ClubAddress.Text = "Address:" + currentClub.ClubAddress + "， " + currentClub.ClubCity;
            Holes.Text= "Holes: "+ currentClub.ClubHoles;
            HCP.Text = "HCP: " + currentClub.ClubHCP;
            ClubImage.Source = new BitmapImage(new Uri(String.Format("Images/{0}.png", currentClub.ClubId), UriKind.Relative));
            
        }

        private void initAppBar()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBarIconButton RouteButton = new ApplicationBarIconButton(new Uri("/Images/appbar.feature.search.rest.png", UriKind.Relative));
            RouteButton.Text = "route";
            RouteButton.Click += new EventHandler(RouteButton_Click);
            ApplicationBar.Buttons.Add(RouteButton);
            ApplicationBarIconButton CommentButton = new ApplicationBarIconButton(new Uri("/Images/appbar.edit.rest.png", UriKind.Relative));
            CommentButton.Text = "comment";
            CommentButton.Click += (o, e) =>
                {
                    Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(String.Format("/Comment.xaml?hashtag={0}", GetHashTag()), UriKind.Relative)));
                };
            ApplicationBar.Buttons.Add(CommentButton);
            ApplicationBarIconButton ShareButton = new ApplicationBarIconButton(new Uri("/Images/appbar.upload.rest.png", UriKind.Relative));
            ShareButton.Text = "share";
            ShareButton.Click += (o, e) => { NavigationService.Navigate(new Uri(String.Format("/FacebookAuth.xaml?clubid={0}", currentClub.ClubId), UriKind.Relative)); };
            ApplicationBar.Buttons.Add(ShareButton);
            ApplicationBarIconButton RefreshButton = new ApplicationBarIconButton(new Uri("/Images/appbar.refresh.rest.png", UriKind.Relative));
            RefreshButton.Text = "refresh";
            RefreshButton.Click += (o, e) => { GetTweets(); };
            ApplicationBar.Buttons.Add(RefreshButton);
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = true;
        }

        void RouteButton_Click(object sender, EventArgs e)
        {
            BingMapsDirectionsTask bingMapsDirectionsTask = new BingMapsDirectionsTask();
            watcher.Start();
            GeoCoordinate destination = currentClub.ClubCoordinate;
            LabeledMapLocation spaceNeedleLML = new LabeledMapLocation(currentClub.ClubName, destination);
            bingMapsDirectionsTask.End = spaceNeedleLML;
            bingMapsDirectionsTask.Show();
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            watcher.Stop();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            GetTweets();
        }

        private void GetTweets()
        {
            var twitterCtx = new TwitterContext();

            (from search in twitterCtx.Search
             where search.Type == SearchType.Search &&
                   search.Hashtag == GetHashTag() &&
                   search.PersonReference == "MolfApp"
             select search).AsyncCallback(result =>
                    Dispatcher.BeginInvoke(() =>
                    {
                        var tweets =
                            (from tweet in result.SingleOrDefault().Results
                             where tweet.Source.Contains("https://twitter.com/MolfApp")
                             select new CommentItem()
                             {
                                 CurrentComment = new CommentModel { User = tweet.FromUserName, Pic = tweet.ProfileImageUrl, Message = tweet.Text }
                             }).ToList();
                        CommentList.ItemsSource = tweets;
                    })
                ).SingleOrDefault();
        }

        private string GetHashTag()
        {
            return currentClub.ClubName.Replace(" ", string.Empty).ToLower();
        }
    }
}